import { useEffect } from "./useEffect";

export function useWindowEvent<K extends keyof WindowEventMap>(event: K, listener: (ev: WindowEventMap[K]) => void) {
  useEffect(() => {
    window.addEventListener(event, listener);
    return () => window.removeEventListener(event, listener);
  });
}

/**
 * 窗口尺寸变化后延迟执行
 * @param ms 延迟时间
 * @param listener 回调
 */
export function useWindowResizeTimeout(ms: number, listener: (ev: WindowEventMap["resize"]) => void) {
  let timeoutId: any = null;
  useWindowEvent("resize", ev => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => listener(ev), ms);
  });
}
